package com.project.oauth2Server.Authorization;

import com.project.oauth2Server.config.AuthConfig;
import com.project.oauth2Server.config.ClientConfig;
import com.project.oauth2Server.config.redis.ClientInfoRedis;
import com.project.thisDatabase.redis.RedisConnectionConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.config.annotation.builders.ClientDetailsServiceBuilder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;

import javax.annotation.Resource;
import java.util.List;

@Configuration
@EnableAuthorizationServer
public class AuthServerConfiguration extends AuthorizationServerConfigurerAdapter {

    @Autowired
    ClientInfoRedis clientInfoRedis;

    @Autowired
    AuthenticationManager authenticationManager;

    ClientDetailsServiceBuilder.ClientBuilder clientBuilder;

    @Autowired
    AuthConfig authConfig;

    @Value(value = "${spring.data.redis.database:}")
    private String dbIndex;

    @Value(value = "${spring.data.redis.host:}")
    private String hostName;

    @Value(value = "${spring.data.redis.port:}")
    private String port;

    @Value(value = "${spring.data.redis.password:}")
    private String password;

    @Value(value = "${spring.data.redis.lettuce.pool.max-idle:}")
    private String maxIdle;

    @Value(value = "${spring.data.redis.lettuce.pool.min-idle:}")
    private String minIdle;

    @Value(value = "${spring.data.redis.lettuce.pool.max-active:}")
    private String maxActive;

    @Value(value = "${spring.data.redis.lettuce.pool.max-wait:}")
    private String maxWait;

    @Value(value = "${spring.data.redis.timeout:}")
    private String timeOut;

    @Value(value = "${spring.data.redis.timeout:}")
    private String shutdownTimeOut;

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
        endpoints
                .tokenStore(tokenStore())
                .authenticationManager(authenticationManager)
                .reuseRefreshTokens(false);
    }

    public void bindClient(ClientConfig cli) {
        bindDetailsBuilder(clientBuilder.and(), cli);
        clientInfoRedis.getExecutor().addListByObject(cli);
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) {
        security.allowFormAuthenticationForClients();
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        List<ClientConfig> cfgs = authConfig.getClients();
        List<ClientConfig> client_list = clientInfoRedis.getExecutor().getList(ClientConfig.class);
        cfgs.addAll(client_list);
        for(ClientConfig cli : cfgs){
            if (null == clientBuilder){
                clientBuilder = bindDetailsBuilder(clients.inMemory(), cli);
            } else {
                clientBuilder = bindDetailsBuilder(clientBuilder.and(), cli);
            }
        }
    }

    private ClientDetailsServiceBuilder.ClientBuilder bindDetailsBuilder(ClientDetailsServiceBuilder bind, ClientConfig cli){
        String secret = new BCryptPasswordEncoder().encode(cli.getPassword());////对密码进行加密
        return bind.withClient(cli.getName())
                .redirectUris(cli.getRedirect())
                .autoApprove(true)
                .resourceIds(cli.getResources())
                .authorizedGrantTypes(cli.getTypes())
                .scopes(cli.getScopes())
                .authorities(cli.getAuthorities())
                .secret(secret)
                .accessTokenValiditySeconds(cli.getValidity().getToken())
                .refreshTokenValiditySeconds(cli.getValidity().getRefresh());
    }

    @Bean
    public TokenStore tokenStore() {
        return new RedisTokenStore(RedisConnectionConfig.createLettuceConnectionFactory(
                Integer.parseInt(dbIndex),
                hostName,
                Integer.parseInt(port),
                password,
                Integer.parseInt(maxIdle),
                Integer.parseInt(minIdle),
                Integer.parseInt(maxActive),
                Long.parseLong(maxWait),
                Long.parseLong(timeOut),
                Long.parseLong(shutdownTimeOut)
        ));
    }
}
